import type { AxiosInstance } from "axios";

export { extractRandomParagraph, getTranslation, range, deleteEverySecondWord };

function extractRandomParagraph(wikiPage: Document): string {
  const paragraphs = wikiPage
    ?.getElementById("content")
    ?.getElementsByTagName("p");

  let randomParagraph = "";

  if (paragraphs !== undefined) {
    const randomIndex = Math.floor(Math.random() * paragraphs.length);
    randomParagraph = [...paragraphs].at(randomIndex)?.innerText ?? "";
  }

  randomParagraph = randomParagraph.replaceAll("&#160;", "");
  return randomParagraph;
}

async function getTranslation(
  libreTranslateClient: AxiosInstance,
  paragraph: string
): Promise<string> {
  const translation = await libreTranslateClient
    .post(
      "/translate",
      {
        api_key: "",
        format: "text",
        source: "fr",
        target: "pl",
        q: paragraph,
      },
      {
        headers: { "Content-Type": "application/json" },
      }
    )
    .then((res) => res.data["translatedText"])
    .catch((error) => {
      console.log(error);
    });

  return translation;
}

function range(start: number, end: number) {
  return Array.from({ length: end - start }, (_, i) => i);
}

function deleteEverySecondWord(str?: string): {
  phrase: string;
  missings: string[];
} {
  if (!str) {
    console.log("no string");
    return { phrase: "", missings: [] };
  }
  let result: string[] = [];
  let missings: string[] = [];
  const parts = str.split(" ");

  let j = 0;

  let replacenext = false;

  for (const i of range(0, parts.length)) {
    const word = parts[i]!;

    if (!replacenext || word.match(/\d/)) {
      result = [...result, word!];
      replacenext = true;
    } else {
      const masked = word.replaceAll(/\p{Letter}/gu, ".");
      const replacement = `<span id="span${j++}" class="gap">${masked}</span>`;

      result = [...result, replacement];

      missings = [...missings, word];

      replacenext = false;
    }
  }
  return { phrase: result.join(" "), missings };
}
